package com.wsjc.common.redis.session;

import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.wsjc.common.redis.RedisUtils;

import redis.clients.jedis.Jedis;

/**
 * 将用户会话信息保存在Redis中的工具类
 */
public class RedisSessionUtils {

	private static Logger logger = Logger.getLogger(RedisSessionUtils.class);
	/**
	 * 默认过期时间
	 */
	private static final Integer DEFAULT_SESSION_TIMEOUT = 60 * 30;

	@Autowired
	private static RedisUtils redisUtils ;
	
	
	/**
	 * 保存session
	 * 
	 * @param sessionId
	 * @param sessionObj
	 * @param seconds
	 *            超时秒数，如果为null则默认为30分钟
	 * @return
	 */
	public static boolean saveSession(String sessionId, Map<String, Object> sessionObj, Integer seconds) {
		boolean result = false;
		Jedis jedis = redisUtils.instanceJedisFactory("agent");
		try {
			if (seconds != null) {
				result = redisUtils.save(jedis, sessionId, sessionObj, seconds);
			} else {
				result = redisUtils.save(jedis, sessionId, sessionObj, DEFAULT_SESSION_TIMEOUT);
			}
		} catch (Exception e) {
			logger.error("缓存删除失败：" + e);
		}finally {
			redisUtils.releaseResource(jedis);
		}
		return result;
	}

	/**
	 * 删除session
	 * 
	 * @param sessionId
	 * @return
	 */
	public static boolean deleteSession(String sessionId) {
		boolean result = false;
		Jedis jedis = redisUtils.instanceJedisFactory("agent");
		try {
			result = redisUtils.del(jedis, sessionId);
		} catch (Exception e) {
			logger.error("缓存删除失败：" + e);
		}finally {
			redisUtils.releaseResource(jedis);
		}
		return result;
	}

	/**
	 * 取session
	 * 
	 * @param sessionId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, Object> getSession(String sessionId) {
		Map<String, Object> sessionObj = null;
		Jedis jedis = redisUtils.instanceJedisFactory("agent");
		try {
			sessionObj = (Map<String, Object>) redisUtils.get(jedis, sessionId);
		} catch (Exception e) {
			logger.error("缓存读取失败：" + e);
		}finally {
			redisUtils.releaseResource(jedis);
		}
		return sessionObj;
	}

	/**
	 * 更新session超时时间
	 * 
	 * @param sessionId
	 * @param seconds
	 * @return
	 */
	public static boolean updateSessionTime(String sessionId, Integer seconds) {
		boolean result = false;
		Jedis jedis = redisUtils.instanceJedisFactory("agent");
		try {
			if (seconds == null) {
				result = redisUtils.expire(jedis, sessionId, DEFAULT_SESSION_TIMEOUT);
			} else {
				result = redisUtils.expire(jedis, sessionId, seconds);
			}
		} catch (Exception e) {
			logger.error("缓存时间更新失败：" + e);
		}finally {
			redisUtils.releaseResource(jedis);
		}
		return result;
	}

}
